package com.witframework.web.tag.utf8;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.BodyContent;
import javax.servlet.jsp.tagext.BodyTagSupport;

import com.witframework.util.StringTools;

public class Utf8Tag extends BodyTagSupport{
  private String id = null;
  private PageContext pageContext;
  private static char[] HEX_DIGIT = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

  public void setId(String paramString)  {
    this.id = paramString;
  }

  public String getId() {
    return this.id;
  }

  public void setPageContext(PageContext paramPageContext) {
    this.pageContext = paramPageContext;
  }

  public int doAfterBody()  throws JspException {
    BodyContent localBodyContent = getBodyContent();
    String str;
    if (localBodyContent == null)
      str = "";
    else if ((str = localBodyContent.getString()) == null)
      str = "";
    str = proceedString(str.toCharArray());
    localBodyContent.clearBody();
    if (this.id != null)
      this.pageContext.setAttribute(this.id, str, 1);
    else
      try {
        JspWriter localJspWriter = localBodyContent.getEnclosingWriter();
        localJspWriter.print(str);
      } catch (Exception localException){
        throw new JspException("Could not save body");
      }
    return 0;
  }

  public int doEngTag()throws JspException{
    dropData();
    return 6;
  }

  private String byteToHex(byte paramByte){
    char[] arrayOfChar = { HEX_DIGIT[(paramByte >> 4 & 0xF)], HEX_DIGIT[(paramByte & 0xF)] };
    return new String(arrayOfChar);
  }

  private String charToHex(char paramChar){
    byte b1 = (byte)(paramChar >>> '\b');
    byte b2 = (byte)(paramChar & 0xFF);
    return byteToHex(b1) + byteToHex(b2);
  }

  private String proceedString(char[] paramArrayOfChar){
    StringBuffer localStringBuffer = new StringBuffer();
    for (int i = 0; i < paramArrayOfChar.length; ++i){
      localStringBuffer.append("\\u");
      localStringBuffer.append(charToHex(paramArrayOfChar[i]));
    }
    return localStringBuffer.toString();
  }

  public void release(){
    dropData();
  }
  private void dropData(){
    this.id = null;
  }
  public static void main(String[] s){
	  Utf8Tag app=new Utf8Tag();
	  System.out.println(app.proceedString("吴新阳".toCharArray()));
	  System.out.println(StringTools.convert("吴新阳"));	  
  }
}